package edu.cornell.lsi.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

// Utility class for session Management implemented as a thread
public class SessionUtil extends Thread{

	public static long sessionId = 1;
	public static HashMap<String,UserSession> sessionData = new HashMap<String,UserSession>();
	private long sessionTimeout = 60000;

	
	public SessionUtil(){
		init();
	}

	// start the background process to remove timed out sessions
	public void init(){
		SessionUtil newThread = new SessionUtil();
		newThread.start();
	}

	// overridden run method
	// remove the timedout session frm session data table
	public void run() { 
		try{
			while(sessionData.size() != 0){

				Set<String> keys = sessionData.keySet();
				for(String key : keys){
					UserSession user = sessionData.get(key);
					String sessionTime = user.getDate();
					if(isTimedOut(sessionTime, "", sessionTimeout) && !user.isInUse()){
						synchronized(this){
							sessionData.remove(key);
						}
					}
				}
				this.wait(sessionTimeout);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	//difference between dates in msec
	public static boolean isTimedOut(String oldDate, String newDate, long timeOut){
		try{
			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date date1 = dateFormat.parse(oldDate);
			Date date2 = dateFormat.parse(newDate);

			if(date2.getTime() - date1.getTime() > timeOut) return true;
			else return false;

		} catch (ParseException e){

			System.out.println("Exception :"+e);    

		}    
		return false;
	}
}
